(function() {
	var initializing = false, fnTest = /xyz/.test(function() {
		xyz;
	}) ? /\b_super\b/ : /.*/;
	this.Class = function() {
	};
	Class.extend = function(prop) {
		var _super = this.prototype;
		initializing = true;
		var prototype = new this();
		initializing = false;
		for ( var name in prop) {
			prototype[name] = typeof prop[name] == "function"
					&& typeof _super[name] == "function"
					&& fnTest.test(prop[name]) ? (function(name, fn) {
				return function() {
					var tmp = this._super;
					this._super = _super[name];
					var ret = fn.apply(this, arguments);
					this._super = tmp;
					return ret;
				};
			})(name, prop[name]) : prop[name];
		}
		function Class(arg) {
			if (arg)
				$.extend(this, arg);
			if (!initializing && this.init)
				this.init.apply(this, arguments);
		}
		Class.prototype = prototype;
		Class.prototype.constructor = Class;
		Class.extend = arguments.callee;
		Class.create = function(arg) {
			return new this(arg);
		};
		return Class;
	};
})();

// 进制后退
document.onkeydown = function(e) {
	if (!e)
		e = window.event;
	if (e
			&& e.target
			&& (e.target.nodeName == "BODY" || e.target.nodeName == "A" || e.target.readOnly == true)
			&& e.keyCode == 8) {
		return false;
	}
}

var __ajaxcount = 0;
var __topwin = window.top;
var __$jq = __topwin.$;
var __istop = (window == window.top);

// 全局 loading提示
$(document).ajaxStart(function() {
	__topwin.__startajax();
});
$(document).ajaxStop(function() {
	__topwin.__stopajax();
});
$(window).error(function() {
	if (jQuery.active > 0) {
		jQuery.active--;
	}
	__topwin.__stopajax();
});
function __startajax() {
	__topwin.__ajaxcount++;
	__$jq("#apploading").css('display', 'block');

}
function __stopajax() {
	__topwin.__ajaxcount--;
	if (__topwin.__ajaxcount <= 0) {
		__topwin.__ajaxcount = 0;
		__$jq("#apploading").css('display', 'none');
	}
}
// 错误处理
$(document).ajaxError(
		function(event, jqxhr, settings, thrownError) {
			__topwin.__stopajax();
			if (__topwin.__errormsg)
				return;
			var msgwin = null;
			/*
			 * if(jqxhr.status == 0){ __topwin.__errormsg = true; msgwin =
			 * __$jq.messager.alert('系统提示',"与服务器连接已经断开！",'warning',function(){
			 * __topwin.__errormsg = false; }); //return; }
			 */

			if (jqxhr.status == 400) {
				__topwin.__errormsg = true;
				msgwin = __$jq.messager.alert('系统提示', jqxhr.statusText,
						'warning', function() {
							__topwin.__errormsg = false;
						});
				app.msg.debug(jqxhr.statusText);
				// return;
			}
			if (jqxhr.status == 403) {
				__topwin.__errormsg = true;
				var msgText = "无法访问，用户权限不足！"
				msgwin = __$jq.messager.alert('系统提示', msgText, 'warning',
						function() {
							__topwin.__errormsg = false;
						});
				app.msg.debug(msgText);
				// return;
			}
			if (jqxhr.status == 404) {
				__topwin.__errormsg = true;
				var url = (arguments[2] ? arguments[2].url : "");
				var msgText = "访问的资源无效，url：" + url;
				msgwin = __$jq.messager.alert('系统提示', msgText, 'warning',
						function() {
							__topwin.__errormsg = false;
						});
				app.msg.debug(msgText);
				// return;
			}
			if (jqxhr.status == 10000) {
				__topwin.__errormsg = true;
				msgwin = __$jq.messager.alert('系统提示', "登陆状态过期，请重新登陆！或账号已经在其他地方登陆。",
						'warning', function() {
							__topwin.__errormsg = false;
							__topwin.location = "login";
						});
				// return;
			}
			if (jqxhr.status == 500) {
				try {
					var msg = $.parseJSON(jqxhr.responseText);
					if (msg.msgtype == 1) {
						__topwin.__errormsg = true;
						var msg_info = msg.msg;
						if(msg.msgid)msg_info = '错误号:'+ msg.msgid + '<br/>' + msg.msg;
						msgwin = __$jq.messager.alert('系统提示', msg_info, 'warning',
								function() {
									__topwin.__errormsg = false;
								});
					} else {
						__topwin.__errormsg = true;
						var msg_info = msg.msg;
						if(msg.msgid)msg_info = '错误号:'+ msg.msgid + '<br/>' + msg.msg;
						msgwin = __$jq.messager.alert('系统提示', msg_info, 'info',
								function() {
									__topwin.__errormsg = false;
								});
					}
					app.msg.debug(jqxhr.responseText);
					// return;
				} catch (ex) {
				}

			}

			if (msgwin) {
				var op = msgwin.window("options");
				op._close = op.onClose;
				op.onClose = function() {
					__topwin.__errormsg = false;
					op._close();
				};
			}

		});

var app = {};
if (__appconfig) {
	$.extend(app, __appconfig);
}
app.$ = $;
/**
 * ajax请求跟踪日志
 */
$(document).ajaxComplete(
		function(event, xhr, settings) {
			if (xhr.getResponseHeader("st_calling_controller")) {
				app.msg.debug("request method\t\t:"
						+ xhr.getResponseHeader("st_request_method")
						+ "\nrequest url \t\t:"
						+ xhr.getResponseHeader("st_request_url")
						+ " \ncalling controller\t:"
						+ xhr.getResponseHeader("st_calling_controller")
						+ " \ncalling method\t\t:"
						+ xhr.getResponseHeader("st_calling_method"));
			}
		});
/**
 * 系统中ajax调用此方法，封装头部信息和记录系统ajax状态
 * 
 * @param args
 */
app.ajax = function(args) {
	// 默认参数
	var op = {
		beforeSend : function(xhr) {
			// if()
			/*
			 * xhr.setRequestHeader('menuid', menuid);
			 * xhr.setRequestHeader('instanceid', instanceid);
			 * xhr.setRequestHeader('moduleid', moduleid);
			 */
		},
		contentType : "application/json;charset=utf-8",
		type : "POST",
		dataType : "json",
		async : true,
		cache : false
	};
	$.extend(op, args);
	if (op.type == "POST" && op.dataType == "json" && op.data)
		op.data = JSON.stringify(op.data);
	var def = $.ajax(op);
	return def;
};

//系统ui加载完毕事件处理
var __ready_deferred = $.Deferred();
if($.parser && $.parser.onComplete){
	$.parser.onComplete = function(arg1){
		__ready_deferred.resolve(arg1);
	};
}else{
	$(document).ready(function(){
		__ready_deferred.resolve();
	});
}
/**
 * 系统ui加载完毕回调注册
 */
app.ready = function(fn){
	__ready_deferred.done(fn);
};

//消息对象
app.msg = {

	/**
	 * 提示信息持续时间，过时自动消失
	 */
	duration : 5000

	/**
	 * 警告信息，需要点确认
	 * 
	 * @param msg
	 */
	,
	alert : function(msg) {
		var _this = this;
		var def = $.Deferred();
		if (_this._msg)
			return def;
		_this._msg = true;

		var kb_fn = function() {
			_this._msg = false;
			def.resolve();
		};
		var win = $.messager.alert('系统警告', msg, 'warning');
		_this._destroy(win,true,kb_fn);
		return def;
	}

	/**
	 * 模态，需要确认的，并返回点击确认还是取消
	 * 
	 * @param msg
	 */
	,
	confirm : function(msg) {

		var _this = this;
		var def = $.Deferred();

		var win = $.messager.confirm('系统确认', msg, function(r) {
			def.resolve(r);
		});

		_this._destroy(win);
		return def;
	}

	/**
	 * 调试信息
	 * 
	 * @param msg
	 */
	,
	debug : function(msg){
		if (typeof console !== 'undefined') {
		     if(console.debug){
		    	 console.debug(msg);
		     }else{
		    	 console.log(msg);
		     }
		  }
	}

	/**
	 * 错误信息
	 * 
	 * @param msg
	 */
	,
	error : function(msg) {
		var _this = this;
		var def = $.Deferred();
		if (_this._msg)
			return def;
		_this._msg = true;
		var kb_fn = function() {
			_this._msg = false;
			def.resolve();
		};
		var win = $.messager.alert('系统提示', msg, 'error');
		_this._destroy(win,true,kb_fn);
		return def;
	}

	/**
	 * 提示信息无需确认
	 * 
	 * @param msg
	 */
	,
	info : function(msg) {
		var _this = this;
		var def = $.Deferred();
		if (_this._msg)
			return def;
		_this._msg = true;
		/*
		 * var win = $.messager.show({ title:'系统提示', msg:msg, showType:'show',
		 * timeout:this.duration, style:{ right:'', bottom:'' } });
		 */
		var kb_fn = function() {
			_this._msg = false;
			def.resolve();
		};
		var win = $.messager.alert('系统提示', msg, 'info');
		_this._destroy(win,true,kb_fn);
		return def;
		
	},
	_destroy : function(win,ke,kb_fn) {
		var _this = this;
		var op = win.window("options");
		op._close = op.onClose;
		//键盘事件
		var ke_fn = function(event){
			//32 空格 13回车
			if(event.keyCode == 13 || event.keyCode == 32){
				win.window("close");
			}
		};
		op.onClose = function() {
			_this._msg = false;
			op._close();
			if(ke){
				$(document).unbind("keyup",ke_fn);
				if(kb_fn)kb_fn();
			}
		};		
		if(ke)$(document).bind("keyup",ke_fn);
	},
	show: function(msg,styleShow) {
		var style= {
								left : '',
								right : 10,
								top : document.body.scrollTop + 10
										+ document.documentElement.scrollTop,
								bottom : ''
							};
		var newStyle=$.extend({},style,styleShow);
	  	$.messager.show({
							title : '提示',
							msg : msg,
							showType : 'show',
							style : newStyle,
							timeout:2500

						});
		 
	}

};


app.log = function(msg) {
	app.msg.debug(msg);
};

// 服务类
app.SvrClass = Class.extend({
	controller : "", // 服务控制器
	get : function(method, arg, para) {
		var pm = {
			url : app.approot + this.controller + "/" + method,
			type : "GET",
			data : arg
		};
		$.extend(pm, para || {});
		return app.ajax(pm).done(function(result) {
			if (result && result.exData)
				app.msg.debug(result.exData.called);
		});
	},
	post : function(method, arg, para) {
		var pm = {
			url : app.approot + this.controller + "/" + method,
			type : "POST",
			data : arg
		};
		$.extend(pm, para || {});
		return app.ajax(pm).done(function(result) {
			if (result && result.exData)
				app.msg.debug(result.exData.called);
		});
	}
});

/**
 * 获取控制器对象
 */
app.controller = function(ctl){
	return app.SvrClass.create({controller:ctl});
};

//

if (!__istop) {
	app.msg = __topwin.app.msg;
}

// 全局参数
if (__appconfig)
	$.extend(app, __appconfig);

var topapp = __topwin.app;

/**
 * 添加一个标签
 * 
 * @param option
 */
app.addIframeTab = function(option) {
	var op = $.extend({
		closable : true
	}, option);
	var $maintabs = __topwin.$('#maintabs');
	var tabs = $maintabs.tabs("tabs");
	for ( var index = 0; index < tabs.length; index++) {
		var top = tabs[index].panel("options");
		if (top.id == op.id) {
			$maintabs.tabs('select', index);
			return;
		}
	}
	var old_onload = op.onLoad;

	$maintabs.tabs('addIframeTab', {
		// tab参数为一对象，其属性同于原生add方法参数
		tab : op,
		iframe : {
			src : option.src
		},
		onload : function(iwin) {
			if (iwin && iwin.app) {
				iwin.app.opener = window;
				iwin.app.currentTabid = op.id;
			}
			if (old_onload)
				old_onload(iwin);
		}
	});
	$maintabs.tabs('addEventParam');

};

/**
 * 关闭指定的标签
 * 
 * @param tabId
 */
app.closeTab = function(tabId) {
	var $maintabs = __topwin.$('#maintabs');
	var tabs = $maintabs.tabs("tabs");
	for ( var index = 0; index < tabs.length; index++) {
		var top = tabs[index].panel("options");
		if (top.id == tabId) {
			$maintabs.tabs('close', index);
			return;
		}
	}
};
/**
 * 关闭当前打开的标签
 */
app.closeCurrentTab = function() {

	var $maintabs = __topwin.$('#maintabs');
	var tab = $maintabs.tabs('getSelected');
	var index = $maintabs.tabs('getTabIndex', tab);
	$maintabs.tabs('close', index);

};

/**
 * 关闭所有标签，除了第一个标签桌面
 */
app.closeAllTab = function() {

	var $maintabs = __topwin.$('#maintabs');
	var tabs = $maintabs.tabs("tabs");
	for ( var index = tabs.length - 1; index > 0; index--) {
		$maintabs.tabs("close", index);
	}

};

/**
 * 遮罩主体
 * 
 * @private
 */
app._getMark = function(id) {
	if (!id)
		id = "__maskid";
	return $('<div id="'
			+ id
			+ '" style="margin:0;padding:0;position:absolute;width:100%;height:100%;background:#ccc;z-index:1000;background:rgb(213, 207, 207);"><div>');
};

/**
 * 遮罩提示信息
 * 
 * @private
 */
app._getMaskMessage = function() {
	return $('<div id="__maskmessage" class="mask-message" style="border-radius: 10px;z-index:3;width:auto;line-height:16px;position:absolute;top:50%;margin:auto;left:50%;margin-top:-40px;margin-left:-40px;border:2px solid #d4d4d4;padding: 12px 5px 10px 30px;background: #ffffff url(\'themes/'
			+ app.theme
			+ '/images/loading16x16.gif\') no-repeat scroll 5px center;">'
			+ ('加载页面...') + '</div>');
};

/**
 * 启动遮罩
 */
app.startMask = function(target, id) {
	if (!target)
		target = $('body');
	var $mark = app._getMark(id).appendTo(target);
	app._getMaskMessage().appentTo($mark);
};

/**
 * 结束遮罩
 */
app.stopMask = function(id) {
	if (!id)
		id = "__maskid";
	var $mask = $("#" + id);
	$("#__maskmessage", $mask).fadeOut('slow', function() {
		$mask.remove();
	});
};
/**
 * 在父窗口弹出对话框
 */
app.dialog = function(option) {

	var holder = __$jq("<div class='st-dialog-box' ></div>");

	holder.appendTo("body");
	if (option.html) {
		holder.append(option.html);
	}

	var op = $.extend(true, {
		width : 500,
		height : 400,
		modal : true,
		mask : true,
		buttons : [ {
			text : ' 关闭 ',
			iconCls : 'icon-cancel',
			handler : function() {
				holder.dialog("destroy");
				holder.remove();
				__topwin.app.currentDialog = null;
			}
		} ],
		onClose : function() {
			holder.dialog("destroy");
			holder.remove();
			__topwin.app.currentDialog = null;
		},
		onloading : function() {
		},
		onload : function() {
		}
	}, option || {});

	var maxheight = __$jq(__topwin).height();
	if (maxheight < op.height)
		op.height = maxheight;

	__topwin.app.currentDialog = holder.dialog(op);

	// 加载iframe
	if (op.src) {

		var $tabBody = holder;
		var $mask = app._getMark().appendTo($tabBody);
		var $maskMessage = app._getMaskMessage().appendTo($mask);

		holder.css("overflow", "hidden");
		var iframe = document.createElement("iframe");
		if (op.src && op.src.indexOf("?") > 0) {
			iframe.src = op.src + "&_rt=" + Math.random();
		} else {
			iframe.src = op.src + "?_rt=" + Math.random();
		}
		
		iframe.frameBorder = 0;
		iframe.height = '100%';
		iframe.width = '100%';
		if (iframe.attachEvent) {
			iframe.attachEvent("onload", function() {
				option.iwin = iframe.contentWindow;
				if (option.iwin.app)
					option.iwin.app.opener = window;
				$.when(op.onloading()).done(
						function(result) {
							op.onload(result);
							$([ $mask[0], $maskMessage[0] ]).fadeOut('slow',
									function() {
										$mask.remove();
									});
						});
			});
		} else {
			iframe.onload = function() {
				option.iwin = iframe.contentWindow;
				if (option.iwin.app)
					option.iwin.app.opener = window;
				$.when(op.onloading()).done(
						function(result) {
							op.onload(result);
							$([ $mask[0], $maskMessage[0] ]).fadeOut('slow',
									function() {
										$mask.remove();
									});
						});
			};
		}
		holder[0].appendChild(iframe);
		if (!op.mask) {
			$mask.remove();
		}
	}

	return holder;

};



/**
 * 获取当前弹出的对话框
 */
app.getCurrentDialog = function() {
	return __topwin.app.currentDialog;
};

// / <summary>
// / 初始化页面
// / 多实体格式
// {entity1:{field1:123,field2:234},entity2:{fiel:123,fiel2:123},otherField:"abc"}
// / HTML:<input field="entity1.field1" /><input field="entity2.fiel" />...
// / 支持多选,多选返回[]
// / </summary>
// / <param name="entity" type="Object">
// / 实体内容
// / </param>
// / <param name="target" type="DOM">
// / 页面区域
// / </param>
// / <param name="selector" type="String">
// / JQuery选择器
// / </param>
app.setform = function(entity, target, selector) {

	if (entity == undefined)
		return;
	if (target == undefined)
		target = this._container;
	selector = selector || 'id';
	var allfileds = $("[" + selector + "]", target);
	var a = "";

	allfileds.each(function(i) {
		var element = $(this);
		var key = element.attr(selector);
		if (key == null || key == "")
			return;
		if (element.attr("type") == "hidden")
			return;

		//var tokens = key.toString().split('.');
		var val;
		/*if (tokens != undefined && tokens.length && tokens.length > 1) {
			var ent = entity[tokens[0]];
			if (typeof entity[tokens[0]] == "undefined")
				return;
			if (ent != undefined)
				val = ent[tokens[1]];
		} else {*/
			val = entity[key];
			if (typeof entity[key] == "undefined")
				return;
		//}

		// if (val != undefined) {
		var easyui_element = $("["+selector+"='"+key+"']", target);
		if (easyui_element.length > 0) {
			if (easyui_element.hasClass("easyui-textbox")) {
				easyui_element.textbox("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-datebox")) {
				easyui_element.datebox("setValue", app.datetimeFormat(val));
				return;
			} else if (easyui_element.hasClass("easyui-numberspinner")) {
				easyui_element.numberspinner("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-combogrid")) {
				easyui_element.combogrid("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-numberbox")) {
				easyui_element.numberbox("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-combobox")) {
				easyui_element.combobox("setValue", val);
				if (easyui_element.combobox("getValue") != val) {
					var op = easyui_element.combobox("options");
					var _old = op.onLoadSuccess;
					op.onLoadSuccess = function(a, b, c) {
						easyui_element.combobox("setValue", val);
						if (_old)
							_old(a, b, c);
					};
				}
				return;
			} else if (easyui_element.hasClass("easyui-combotree")) {
				easyui_element.combotree("setValue", val);
				if (easyui_element.combotree("getValue") != val) {
					var op = easyui_element.combotree("options");
					var _old = op.onLoadSuccess;
					op.onLoadSuccess = function(a, b, c) {
						easyui_element.combotree("setValue", val);
						if (_old)
							_old(a, b, c);
					};
				}
				return;
			} else if (easyui_element.hasClass("easyui-combogrid")) {
				easyui_element.combogrid("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-datetimebox")) {
				easyui_element.datetimebox("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-datetimespinner")) {
				easyui_element.datetimespinner("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-timespinner")) {
				easyui_element.timespinner("setValue", val);
				return;
			}
		}

		if (val && val.constructor && val.constructor == Date) {
			val = app.datetimeFormat(val);
		}

		if (element.attr("type") == "radio") {
			$("[name='" + element.attr("name") + "']", target).each(function() {
				if ($(this).val() == (val+""))
					$(this).prop("checked", true);
				else
					$(this).prop("checked", false);
			});
		} else if (element.attr("type") == "checkbox") {
			if (val && val.length) {
				$.each(val, function(index) {
					var thatelemetn = $("[name='" + element.attr("name")
							+ "'][value='" + val[index] + "']", target);
					thatelemetn.prop("checked", true);
				});
			} else {
				if (element.prop("value") == (val+"")) {
					$(this).prop("checked", true);
				} else {
					$(this).prop("checked", false);
				}
			}
		} else if (element.hasClass("textbox-span")) {
			if (val != null) {
				element.text(val);
			}else{
				element.text("");
			}
		} else if (!(element.is('input') || element.is('textarea') || element
				.is('select'))) {
			if(val != null)
			element.text(val);
			else{
				element.text("");
			}
		} else {
			if(val != null)
				element.val(val);
			else
				element.val("");
		}
		// }
	});
	if (target && target.form)
		target.form("validate");
};

// / <summary>
// / 根据属性field 从指定的页面区域获取内容 , 返回实体 :{NavId="...",NavName=".."}
// / 多实体格式
// {entity1:{field1:123,field2:234},entity2:{fiel:123,fiel2:123},otherField:"abc"}
// / 对选支持:格式[]
// / </summary>
// / <param name="target" type="DOM">
// / 页面区域
// / </param>
// / <param name="nullable" type="boolean">
// / 是否获取null的属性字段
// / </param>
// / <return>
// / 实体内容
// / </return>
app.getform = function(target, nullable) {

	if (nullable == undefined)
		nullable = true;

	var entity = {};
	if (target == undefined)
		target = this._container;

	var allfileds = $("[id]", target);

	allfileds.each(function(i) {
		var element = $(this);
		var key = element.attr("id");
		if (key == null || key == "")
			return;
		if (element.attr("type") == "hidden")
			return;

		//var tokens = key.toString().split('.');

		var tokevalue = function(v) {
			if (v == "")
				v = null;
			if (!nullable && v == null)
				return;
			// / <summary>
			// / 实体赋值
			// / </summary>
		/*	if (tokens != undefined && tokens.length && tokens.length > 1) {
				if (entity[tokens[0]] == undefined)
					entity[tokens[0]] = {};
				entity[tokens[0]][tokens[1]] = v;
			} else {*/
				entity[key] = v;
			//}
		};

		var easyui_element = $("[id='"+key+"']", target);
		if (easyui_element.length > 0) {
			if (easyui_element.hasClass("easyui-textbox")) {
				tokevalue(easyui_element.textbox("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-datebox")) {
				tokevalue(easyui_element.datebox("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-numberspinner")) {
				tokevalue(easyui_element.numberspinner("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-combogrid")) {
				tokevalue(easyui_element.combogrid("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-numberbox")) {
				tokevalue(easyui_element.numberbox("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-combobox")) {
				tokevalue(easyui_element.combobox("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-combotree")) {
				tokevalue(easyui_element.combotree("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-combogrid")) {
				tokevalue(easyui_element.combogrid("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-datetimebox")) {
				tokevalue(easyui_element.datetimebox("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-datetimespinner")) {
				tokevalue(easyui_element.datetimespinner("getValue"));
				return;
			} else if (easyui_element.hasClass("easyui-timespinner")) {
				tokevalue(easyui_element.timespinner("getValue"));
				return;
			}
		}

		// 根据元素不同做不同处理
		if (element.attr("type") == "radio") {
			$("[name='" + element.attr("name") + "']", target).each(function() {
				var r = $(this);
				if (r.attr("checked")) {
					tokevalue(r.val());
				}
			});
		} else if (element.attr("type") == "checkbox") {
			var last = [];
			$("[name='" + element.attr("name") + "']", target).each(function() {
				var r = $(this);
				if (r.attr("checked")) {
					last.push(r.val());
				}
			});
			tokevalue(last);
		} else {
			tokevalue($(this).val());
		}
	});

	return entity;

};

app.stateFormat = function(value) {
	switch (value) {
	case 1:
	case "1":
	case true:
	case "Y":
	case "y":
	case "YES":
	case "yes":
	case "true":
	case "TRUE":
		return "有效"
		break;
	case 0:
	case "0":
	case false:
	case "N":
	case "n":
	case "NO":
	case "no":
	case "false":
	case "FALSE":
		return "无效"
	default:
		return value;
	}
}

/**
 * 短日期格式
 * 
 * @param time
 * @returns {*}
 */
app.datetimeShortFormat = function(time) {
	return app.datetimeFormat(time, false);
}
/**
 * 日期格式化
 * 
 * @param time
 * @param longdatetime
 *            长日期格式包括时间
 * @returns {*}
 */
app.datetimeFormat = function(time, longdatetime) {

	if (time == null || time == "")
		return null;
	var d = new Date();
	if (typeof (time) == "number")
		d.setTime(time);
	else if (typeof (time) == "object")
		d = time;
	else if (typeof (time) == "string") {
		if (longdatetime) {
			return time;
		}
		if (time.length > 10) {
			return time.substring(0, 10);
		}
		return time;
	}
	var year = d.getFullYear();
	var month = d.getMonth() < 9 ? ("0" + (1 + d.getMonth())) : (1 + d
			.getMonth());
	var day = d.getDate() < 10 ? ("0" + d.getDate()) : d.getDate();
	var hour = d.getHours() < 10 ? ("0" + d.getHours()) : d.getHours();
	var minute = d.getMinutes() < 10 ? ("0" + d.getMinutes()) : d.getMinutes();
	var second = d.getSeconds() < 10 ? ("0" + d.getSeconds()) : d.getSeconds();

	if (!longdatetime)
		return year + "-" + month + "-" + day;

	return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":"
			+ second;
};

/**
 * 初始化上传控件 参数帮助文档：http://www.plupload.com/docs/Options
 * 
 * @param option
 */
app.initUploader = function(option) {

	var $container = $("#" + option.container);

	/*
	 * if(!option.browse_button){ option.browse_button = "_"+Math.random();
	 * option.browse_button = option.browse_button.substring(3);
	 * $container.prepend('<a id="'+option.browse_button+'"
	 * href="javascript:void();">[选择文件]</a>'); }
	 * 
	 * if(!option.filelist){ option.filelist = "_"+Math.random();
	 * option.filelist = option.filelist.substring(3); $container.prepend("<div
	 * id='"+option.filelist+"'></div>"); }
	 */

	var $filelist = $('#' + option.filelist, $container);
	if ($filelist.length == 0)
		$filelist = $('#' + option.filelist);

	var _op = $
			.extend(
					{
						runtimes : 'html5,flash,silverlight,html4',
						browse_button : null, // 选择文件按钮
						container : null, // 容器div
						filelist : null,// 显示文件列表的div
						max_file_size : (app.uploadmaxsize ? app.uploadmaxsize
								+ 'mb' : '20mb'),
						chunk_size : '1mb',
						url : app.approot + 'Plupload/upload', // 上传路径
						flash_swf_url : app.approot
								+ 'scripts/plupload/Moxie.swf',
						silverlight_xap_url : app.approot
								+ 'scripts/plupload/Moxie.xap',
						prevent_duplicates : true,// 不允许重复上传相同名字的文件名
						max_retries : 3, // 上传失败重试次数
						multi_selection : true, // 选择多个文件
						unique_names : true,// 重命名文件唯一
						filters : [ {
							title : "附件",
							extensions : "jpg,gif,png,doc,docx,pdf,xls,xlsx"
						} // 文件选择过滤
						// ,{title : "Zip files", extensions : "zip"}
						],
						init : {
							PostInit : function() {
								// $filelist.empty();
							},
							FilesAdded : function(up, files) {
								if (up.getOption().multi_selection != true
										&& $filelist
										&& $filelist.children().length > 0) {
									if (up.files.length > 0) {
										up
												.removeFile(up.files[up.files.length - 1]);
										app.msg
												.alert("只只允许上传一个文件，请先删除已经选中的文件！");
										return;
									}
								}
								plupload
										.each(
												files,
												function(file) {
													$filelist
															.append('<div id="'
																	+ file.id
																	+ '">'
																	+ file.name
																	+ ' ('
																	+ plupload
																			.formatSize(file.size)
																	+ ') <b id="progress_'
																	+ file.id
																	+ '"></b> &nbsp;<a href="javascript:void(0)" title="删除" id="remove_'
																	+ file.id
																	+ '">[X]</a> </div>');
													$("#remove_" + file.id,
															$filelist)
															.click(
																	function() {
																		up
																				.removeFile(file);
																		$(
																				"#"
																						+ file.id)
																				.remove();
																		if (file.target_name) {
																			app
																					.ajax({
																						url : app.approot
																								+ 'Plupload/remove',
																						data : file.target_name
																					});
																		}
																	});
												});
							},
							UploadProgress : function(up, file) {
								$("#progress_" + file.id).text(
										file.percent + "%");
							},
							Error : function(up, err) {
								if (up.getOption() && up.getOption()._deferred) {
									up.getOption()._deferred.reject(err.code
											+ ": " + err.message);
								}
								app.msg.error(err.code + ":" + err.message);
								// app.log("\nError #" + err.code + ": " +
								// err.message);
							},
							FileUploaded : function(up, file, info) {
								if (up.getOption().multi_selection != true) {
									if (up.files.length > 1) {
										up
												.removeFile(up.files[up.files.length - 1]);
										app.msg
												.alert("只只允许上传一个文件，请先删除已经选中的文件！");
										return;
									}
								}
								if (up.files[up.files.length - 1].id == file.id) {
									if (up.getOption()._deferred) {
										up.getOption()._deferred
												.resolve(up.files);
									}
									var count = up.files.length;
									for ( var index = count - 1; index >= 0; index--) {
										up.removeFile(up.files[index]);
									}
								}
							}
						}
					}, option);
	/**
	 * 参数帮助文档：http://www.plupload.com/docs/Options
	 * 
	 * @type {Uploader}
	 */
	var _uploader = new plupload.Uploader(_op);
	_uploader.init();

	/**
	 * 触发上传事件
	 * 
	 * @returns {*}
	 */
	_uploader.upload = function() {
		var def = $.Deferred();
		if (this.files.length == 0) {
			def.resolve([]);
			return def;
		}
		this.getOption()._deferred = def;
		this.start();
		return def;
	};

	/**
	 * 清空上传文件
	 */
	_uploader.clear = function() {
		var count = this.files.length;
		for ( var index = count - 1; index >= 0; index--) {
			this.removeFile(this.files[index]);
		}
		$filelist.empty();
		this.unbindAll();
		this.destroy();
		$container.children().each(function(index, item) {
			if (item.id != option.browse_button && item.id != "fileviewid") {
				$(item).remove();
			}
		});
		$container.data("uploader", null);
	};

	/**
	 * 添加多个文件到文件列表显示
	 * 
	 * @param file
	 * @param callback
	 * @param view ,
	 *            true:只读
	 */
	_uploader.addfiles = function(files, callback, view) {

		for ( var index = 0; index < files.length; index++) {
			var file = files[index];

			var html = '<div style="padding:2px;" id="'
					+ file.attachid
					+ '"><a id="link_'
					+ file.attachid
					+ '" class="easyui-menubutton" data-options="menu:\'#fileoperate_'
					+ file.attachid
					+ '\'" href="javascript:void(0);" title="点击预览">'
					+ (index + 1) + "、" + file.displayname + '</a> ('
					+ plupload.formatSize(file.filesize * 1024)
					+ ') <b id="progress_' + file.attachid + '"></b>';
			html += (' &nbsp;' + app.datetimeFormat(file.createdate, true) + '&nbsp;');
			if (!view) {
				html += ' &nbsp;<a href="javascript:void(0)" title="删除" id="remove_'
						+ file.attachid + '">[X]</a> ';
			}

			html += '</div>';
			html += '<div id="fileoperate_'
					+ file.attachid
					+ '">'
					+ '<span class="icon-large-smartart">&nbsp;&nbsp;&nbsp;&nbsp;</span><a target="_blank" href="'
					+ app.approot
					+ 'Attachment/docview/'
					+ files[index].attachid
					+ '" style="margin-left:15px;">查看</a>'
					+ '<br /><span class="icon-save">&nbsp;&nbsp;&nbsp;&nbsp;</span><a target="_blank" href="'
					+ app.approot + 'Attachment/download/'
					+ files[index].attachid
					+ '" style="margin-left:15px;">下载</a>' + '</div>';
			$filelist.append(html);
			if (!view) {
				$("#remove_" + file.attachid, $filelist)
						.data("file", file)
						.click(
								function() {

									var filedata = $(this).data("file");

									app.msg
											.confirm(
													"确定删除附件:"
															+ filedata.displayname)
											.done(
													function(result) {
														if (!result)
															return;
														if (callback) {
															callback(filedata);
														} else {
															app
																	.ajax({
																		url : app.approot
																				+ "Attachment/delete/"
																				+ filedata.attachid
																	});
														}
														$(
																"#"
																		+ filedata.attachid,
																$filelist)
																.remove();

													});
								});
			}

			/*
			 * $("#link_"+file.attachid).tooltip({ content: $('<div><img
			 * style="width:200px;height:150px;"
			 * src="'+app.approot+'Attachment/view/'+file.attachid+'.jpg"></div>'),
			 * //showEvent: 'click', position:'right' });
			 */
			$("#link_" + file.attachid).menubutton({

			});

		}

	};

	/**
	 * 添加单个文件到文件列表
	 * 
	 * @param file
	 * @param callback
	 */
	_uploader.addfile = function(file, callback) {
		this.addfiles([ file ], callback);
	};

	$container.data("uploader", _uploader);
	return _uploader;
};

/**
 * 报表打印 printType: 0.打开打印对话框 1.直接打印没有打印对话框 2.打开预览窗口
 */
function print_report(url, printType) {
	if (!printType)
		printType = 0;

	// checkPlugin();
	var printer = $("#report_printer");

	if (printer.length == 0) {
		app.msg.info("打印控件尚未安装，请安装打印控件.");
		return;
	}
	// check plugin is installed
	try {
		printer[0].isOk();
	} catch (ex) {
		app.msg.info("打印控件尚未安装，请安装打印控件.");
		return;
	}

	var url = "http://" + window.location.host + app.approot + url;
	// url ="http://"+window.location.host+
	// this.app.approot+"Reports/print/?report=";

	var urls = [ url ];
	// urls = [url+"report2",url+"report3"];

	try {
		var ret = printer[0].printReport(urls, printType, app.sessionId);

		if (ret) {
			app.msg.info(ret);
		} else if (printType == 1) {
			app.msg.info("打印任务发送完毕!");
		}
	} catch (ex) {
		app.msg.info(ex.message);
		/*
		 * if(console) console.log(ex.message);
		 */
	}

}
/**
 * 插入插件
 */
function checkPlugin() {

	var container = $("#report_plugin_container");
	if (container.length > 0) {
		return;
	}

	container = $("<div id='report_plugin_container'></div>");
	var plugin = $("#report_plugin");
	container.append(plugin);
	container.appendTo("body");
	plugin.show();

}
/**
 * 对html进行转义，显示文本
 * 
 * @param str
 * @returns {string}
 */
app.htmlEncode = function(str) {
	var div = document.createElement("div");
	div.appendChild(document.createTextNode(str));
	return div.innerHTML;
}
/**
 * 对于转义的html字符串解码，显示html
 * 
 * @param str
 * @returns {string}
 */
app.htmlDecode = function(str) {
	var div = document.createElement("div");
	div.innerHTML = str;
	return div.innerHTML;
}

/*
 * 提交表单,下载专用
 */
app.postForm = function(url, arg) {

	// create the form
	var form = $("<form ></form>");
	form.prop({
		'accept-charset' : 'utf-8',
		method : 'post',
		action : url,
		enctype : 'multipart/form-data'
	});
	form.hide();
	form.appendTo("body");

	// add the data
	if (arg) {
		for ( var name in arg) {
			var input = $("<input></input>");
			var v = arg[name];
			if (v != null) {
				if (typeof (v) == "object") {
					v = JSON.stringify(v);
				}
				input.prop({
					type : "hidden",
					name : name,
					value : v
				});
				input.appendTo(form);
			}
		}
	}
	// submit
	form[0].submit();
	form.remove();
}

app.doaction = function(dom, fn) {
	dom.linkbutton("disable");
	$(window).error(function() {
		dom.linkbutton("enable");
	});
	$.when(fn.call(dom)).always(function() {
		dom.linkbutton("enable");
	});

}
/**
 * 流程实例状态
 * 
 * @param value
 * @returns {*}
 */
app.workflow_caseStatusFormat = function(value) {
	if (value == "Executing") {
		return "正在运行";
	} else if (value == "Suspended") {
		return "用户挂起";
	} else if (value == "Cancelled") {
		return "用户取消";
	} else if (value == "Completed") {
		return "结束";
	} else if (value == "Abort") {
		return "异常中断";
	}
	return value;
}
/**
 * 任务状态格式化
 * 
 * @param value
 */
app.workflow_taskStatusFormat = function(value) {

	if (value == "Executing") {
		return "待办";
	} else if (value == "InProgress") {
		return "正在处理";
	} else if (value == "Cancelled") {
		return "已取消";
	} else if (value == "Completed") {
		return "已办结";
	} else if (value == "Rollbacked") {
		return "已回退";
	} else if (value == "Suspended") {
		return "用户挂起";
	}
	return value;
}
/**
 * 审查结果格式化
 * 
 * @param value
 */
app.workflow_taskResultFormat = function(value) {
	if (value == "1") {
		return "通过";
	} else if (value == "0") {
		return "不通过";
	}
	return value;
}
/**
 * 节点类型
 * 
 * @param value
 * @returns {*}
 */
app.workflow_tranTypeFormat = function(value) {
	if (value == "user") {
		return "人工处理";
	} else if (value == "auto") {
		return "自动处理";
	} else if (value == "subflow") {
		return "子流程";
	}
	return value;
}
/**
 * 判断是否是谷歌浏览器
 */
app.ischrome = function() {
	return window.cefQuery || ($.browser.chrome && chrome.runtime);
}
/**
 * 加密狗nativeMessage host id
 * 
 * @type {string}
 * @private
 */
app._lock_hostid = "ibcgeknbeljelbedjnlfilnfecnbafmg";
/**
 * 锁操作
 * 
 * @param cmd
 *            读锁 {cmd:"read",start:"26",length:"25"} 写锁
 *            {cmd:"write",start:"26",data:"abc"}
 * @returns 返回结果 {cmd:"..",status:"0",data:"..."}
 */
app.lock_do = function(cmd) {
	if(window.cefQuery){
		return app.client(cmd);
	}
	var def = $.Deferred();
	chrome.runtime.sendMessage(app._lock_hostid, cmd, function(result) {
		/*
		 * if(!result){ app.msg.info("加密狗可扩展未安装!"); return; }
		 */
		def.resolve(result);
	});
	return def;
};
if (typeof(console) == "undefined") {
	window.console = {
		log : function(){},
		debug :function(){},
		info:function(){}
	};
}


app.clearForm = function(entity, target, selector) {

	if (entity == undefined)
		return;
	if (target == undefined)
		target = this._container;
	selector = selector || 'id';
	var allfileds = $("[" + selector + "]", target);
	var a = "";

	allfileds.each(function(i) {
		var element = $(this);
		var key = element.attr(selector);
		if (key == null || key == "")
			return;
		if (element.attr("type") == "hidden")
			return;

		var val;
			val = '';
			/*if (typeof entity[key] == "undefined")
				return;*/
		var easyui_element = $("["+selector+"='"+key+"']", target);
		if (easyui_element.length > 0) {
			if (easyui_element.hasClass("easyui-textbox")) {
				easyui_element.textbox("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-datebox")) {
				easyui_element.datebox("setValue", app.datetimeFormat(val));
				return;
			} else if (easyui_element.hasClass("easyui-numberspinner")) {
				easyui_element.numberspinner("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-combogrid")) {
				easyui_element.combogrid("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-numberbox")) {
				easyui_element.numberbox("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-combobox")) {
				easyui_element.combobox("setValue", val);
				if (easyui_element.combobox("getValue") != val) {
					var op = easyui_element.combobox("options");
					var _old = op.onLoadSuccess;
					op.onLoadSuccess = function(a, b, c) {
						easyui_element.combobox("setValue", val);
						if (_old)
							_old(a, b, c);
					};
				}
				return;
			} else if (easyui_element.hasClass("easyui-combotree")) {
				easyui_element.combotree("setValue", val);
				if (easyui_element.combotree("getValue") != val) {
					var op = easyui_element.combotree("options");
					var _old = op.onLoadSuccess;
					op.onLoadSuccess = function(a, b, c) {
						easyui_element.combotree("setValue", val);
						if (_old)
							_old(a, b, c);
					};
				}
				return;
			} else if (easyui_element.hasClass("easyui-combogrid")) {
				easyui_element.combogrid("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-datetimebox")) {
				easyui_element.datetimebox("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-datetimespinner")) {
				easyui_element.datetimespinner("setValue", val);
				return;
			} else if (easyui_element.hasClass("easyui-timespinner")) {
				easyui_element.timespinner("setValue", val);
				return;
			}
		}

		if (val && val.constructor && val.constructor == Date) {
			val = app.datetimeFormat(val);
		}

		if (element.attr("type") == "radio") {
			$("[name='" + element.attr("name") + "']", target).each(function() {
				if ($(this).val() == (val+""))
					$(this).prop("checked", true);
				else
					$(this).prop("checked", false);
			});
		} else if (element.attr("type") == "checkbox") {
			if (val && val.length) {
				$.each(val, function(index) {
					var thatelemetn = $("[name='" + element.attr("name")
							+ "'][value='" + val[index] + "']", target);
					thatelemetn.prop("checked", true);
				});
			} else {
				if (element.prop("value") == (val+"")) {
					$(this).prop("checked", true);
				} else {
					$(this).prop("checked", false);
				}
			}
		} else if (element.hasClass("textbox-span")) {
			if (val != null) {
				element.text(val);
			}else{
				element.text("");
			}
		} else if (!(element.is('input') || element.is('textarea') || element
				.is('select'))) {
			if(val != null)
			element.text(val);
			else{
				element.text("");
			}
		} else {
			if(val != null)
				element.val(val);
			else
				element.val("");
		}
		// }
	});
	if (target && target.form)
		target.form("validate");
};

app.highcharts = function(element, p) {
    /*var colorsArr = [ '#4572A7', '#DB843D', '#708090', '#89A54E', '#80699B', '#3D96AE',
     '#92A8CD', '#A47D7C', '#B5CA92', '#5F9EA0',
     '#AA4643', '#D8BFD8', '#9ACD32', '#C71585', '#B22222',
     '#2F4F4F', '#9370DB', '#800080', '#48D1CC', '#90EE90'];*/
   /*  var colorsArr = [ '#a2ec88', '#88a9eb', '#edc989', '#ed898b', '#89cfed', '#ede789',
     '#89edd4', '#ed89cb', '#b489ed', '#676dbe'];*/
     var colorsArr = ['#abe78d','#86dbd4','#ecd257','#e97373','#71b68a',
			        '#eca861','#85b3ee','#f1e1a5','#a688de','#a1e2c2',
			        '#f458e6','#f48989','#e6b0ed','#6ce8f4','#5a679e',
			        '#8745ef','#93564d','#a07d6b','#933b3b','#7f5d7a'];
      var divchart={};
     if(typeof(element) == "string"){
     	divchart= {
             renderTo : element,
             defaultSeriesType : "column",
             zoomType : null
         }
     }else{
           divchart= {
             defaultSeriesType : "column",
             zoomType : null
         }
     }
     var defaultOptions = {
         // 图表配置默认值
         chart : divchart,
         // 图例颜色集合
         colors : colorsArr,
         // 这种图的默认值
         plotOptions : {
             column : {
                 dataLabels : {
                     enabled : true,
                     formatter : function() {
                         return this.series.name + ":" + this.y;
                     }
                 }
             },
             line : {
                 dataLabels : {
                     enabled : true
                 }
             },
             pie : {
                 allowPointSelect : true,
                 dataLabels : {
                     enabled : true,
                     formatter : function() {
                         var ss = 0;
                         if (this.total) {
                             ss = (this.y / this.total) * 100;
                             ss = ss.toFixed(2);
                         }
                         return this.point.name + ": " + ss+ "%";

                     }
                 }
             }
         },
         // 禁止水印
         credits : {
             enabled : false
         },
         // X坐标
         xAxis : {
             categories : null
         },
         // 数据
         series : null,
         //禁止导出
         exporting: {enabled:false, buttons: { exportButton: { enabled: false}} },
         // 鼠标经过图表的提示信息
         tooltip : {
             formatter : function() {
                 // 非饼图
                 if (this.x) {
                     return this.x
                         + ":" + this.y;
                 }
                 // 饼图
                 return this.series.name + "<br/>"
                     + this.point.name + ":" + this.point.y;
             }
         },
         lang : {
             decimalPoint : ".",
             printChart:'打印图表',
             downloadPNG : "下载PNG图片",
             downloadJPEG : "下载JPEG图片",
             downloadPDF : "下载PDF文档",
             downloadSVG : "下载SVG矢量图",
             exportButtonTitle : "导出图表",
             loading : "加载...",
             months : [ '1月', '2月', '3月', '4月', '5月', '6月',
                 '7月', '8月', '9月', '10月', '11月', '12月' ],
             printButtonTitle : "打印图表",
             resetZoom : "恢复缩放",
             resetZoomTitle : "恢复缩放比例 1:1",
             thousandsSep : ",",
             weekdays : [ '星期日', '星期一', '星期二', '星期三', '星期四',
                 '星期五', '星期六' ]
         },xAxisLabelRotation:true//是否开启默认的倾斜方式
         ,xAxisLabelRotationCount:12//超过几列倾斜
         ,xAxisLabelRotationStyle:{
             align : "left",
             style : {
                 font : 'normal 12px 宋体'
             },
             rotation : 45// 字体倾斜
         }
     };
     var ops = $.extend(true, defaultOptions, p);
     if(p.tooltip.pointFormat){
     	ops.tooltip=p.tooltip;
     }
     if (ops.xAxis&&ops.xAxisLabelRotation) {
         var Xcategories = ops.xAxis;
         var coun = ops.xAxisLabelRotationCount!=null?ops.xAxisLabelRotationCount:20;//x轴超过0列就字体倾斜
         var xlabel =  ops.xAxisLabelRotationStyle;
         if ($.isArray(Xcategories)) {
             for (var index = 0; index < Xcategories.length; index++) {
                 if (Xcategories[index].categories
                     && Xcategories[index].categories.length > coun) {
                     Xcategories[index].labels = Xcategories[index].labels
                         ? Xcategories[index].labels
                         : xlabel;
                 }
             }
         } else {
             if (Xcategories.categories
                 && Xcategories.categories.length > coun) {
                 Xcategories.labels = Xcategories.labels
                     ? Xcategories.labels
                     : xlabel;
             }
         }
     }
     if(typeof(element) == "string"){
     return  new Highcharts.Chart(ops);
     }else{
      return  element.highcharts(ops);
     }
 };
 
//刷新ABC申请李彪
 app.reloadAbcApply = function()
 {
 	if(__topwin.reloadAbcApply != undefined){
 		__topwin.reloadAbcApply();
 	}
 };
 //关闭申请弹窗
 app.closeApply=function(){
	 if(__topwin.closeApply != undefined){
		 __topwin.closeApply();
	 }
 }
//关闭审批弹窗
 app.closeReg=function(){
	 if(__topwin.closeReg != undefined){
		 __topwin.closeReg();
	 }
 }
 
//刷新ABC审核列表
 app.reloadAbcFlowApply = function()
 {
 	if(__topwin.reloadAbcFlowApply != undefined){
 		__topwin.reloadAbcFlowApply();
 	}
 };
 
 app.reloadRenewForCityApply = function()
 {
 	if(__topwin.reloadRenewForCityApply != undefined){
 		__topwin.reloadRenewForCityApply();
 	}
 };


 /**
  * 判断客户端是否有效
  */
 app.client_valid = function(){
 	return window.cefQuery ? true : false;
 }
 /**
  * 客户端通讯
  */
 app.client = function(cmd){
 	var def = $.Deferred();
 	if(window.cefQuery){
 		 window.cefQuery({
 			 request:JSON.stringify(cmd),
 			 onSuccess:function(mac){
 				 	if(mac){
 				 		def.resolve(JSON.parse(mac));
 				 	}else{
 				 		def.resolve();
 				 	}
 			 },
 			 onFailure: function(error_code, error_message) {
 				 	app.msg.alert(error_code+error_message);
 				 	def.reject(error_code+error_message);
 					console.error(error_code + error_message);
 			}
 		 });
 	}else{
 		//app.msg.alert("该浏览器不支持此操作，请使用指定浏览器。");
 	}
 	return def;
 };

 /**
  * 客户端打印
  * m_controller : 实现了queryPaper方法的控制器
  * papercode : 纸张编号
  * review : 是否预览
  * args : 自定义参数
  */
 app.client_print = function(m_controller,papercode,review,args){
 	if(!app.client_valid()){
 		app.msg.alert("该浏览器不支持此打印，请使用指定浏览器。");
 		return;
 	}
 	var def = $.Deferred();
 	if(!m_controller){
 		m_controller = app.controller("Paper");
 	}

 	//var papercode = "纸张编号";
 	app.client({cmd:"mac"}).done(function(info){
 	 	args = args || {};
 	 	args.papercode = papercode;
 	 	args.pmac = info.mac;
 		m_controller.post('queryPaper',args).done(function(config_paper){
 			//客户端打印参数
 			var cmd = {
 					cmd:"print",//打印命令
 					job:papercode,//打印任务名称
 					paper:config_paper.paper,//纸张设置
 					"review":review,//true为预览
 					pages:[
 					       {positions:config_paper.positions}//一页的打印位置信息
 					       //更多页打印位置传入
 					       ]
 			};
 			//多页打印
 			if(config_paper.pages){
 				cmd.pages = config_paper.pages;
 			}
 			//打印
 			app.client(cmd).done(function(rt){
 				if(rt && rt.status <0){
 					app.msg.alert(rt.msg);
 				}else{
 					def.resolve(config_paper);
 					if(review){
 						var pages_html = "";
 						for(var index = 0;index < rt.pages.length;index++){
 							pages_html += '<div><img src ="client://tmp/'+rt.pages[index]+'" style="width:'+rt.paper.width*0.1+'px;height:'+rt.paper.height*0.1+'px"><div>';
 						}console.log(rt);
 						var dl_editor;
 						var dl_option = {"title":"打印预览", 
 								html:pages_html,
 								height:rt.paper.height*0.1 + 50,
 								width:rt.paper.width*0.1 + 40,
 						        buttons:[ {
 						                text:' 关闭 ',
 						                iconCls:'icon-cancel',
 						                handler:function(){
 						                	dl_editor.dialog("destroy");
 						                	dl_editor.remove();
 						                }
 						            }]
 						    };
 						dl_editor = app.dialog(dl_option);
 					}
 				}
 			});
 		});				
 	});	
 	return def;
 };

 /**
  * 客户端更新
  */
 app.client_update = function(){
 	if(!app.client_valid())return;
 	var controller = app.controller("Application");
 	//获取参数
 	controller.get("getapp?rootmenuid=").done(function(app_info){
 		
 		//app_info.parameters.client_update_url = "http://192.168.1.90:8080/jscesis/share/SafetyExplorer.zip";
 		//app_info.parameters.client_update_version = 1003;
 		//获取客户端版本
 		app.client({"cmd":"version"}).done(function(v_info){
 			//v_info.version = 1001;
 			//是否需要更新
 			if(!app_info.parameters.client_update_version || app_info.parameters.client_update_version <= v_info.version)return;
 			//下载更新包
 			app.client({"cmd":"download","url":app_info.parameters.client_update_url,"target":"client_update.zip","callback":"app.client_update_progress"}).done(function(){
 				var msg_info = app_info.parameters.client_update_msg;
 				if(!msg_info)msg_info="客户端更新，点击【确定】更新并重启客户端";
 				//更新客户端
 				app.client({"cmd":"update","target":"client_update.zip","msg":msg_info});
 			});
 		});
 	});
 };
 /**
  * 客户端更新进度
  */
 app.client_update_progress = function(request_id,current,total){
 	
 };
